#pragma once
#include <mysql.h>
#include <string>
#include <iostream>

class Util
{
public:
    Util() {}
    ~Util() {}
public:
    // 初始化MySQL
    static bool initMysql()
    {
        // 创建MySQL句柄
        my = mysql_init(NULL);
        // 设置字符编码
        mysql_set_character_set(my, "utf8");
        // 连接MySQL
        if (mysql_real_connect(my, ip.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, NULL, 0) == NULL)
        {
            std::cout << "初始化MySQL失败" << std::endl;
            return false;
        }    
        return true;
    }

    static bool findUser(const std::string& user, const std::string& passwd)
    {
        std::string sql = "SELECT user, passwd FROM login WHERE user=\'";
        sql += user;
        sql += "\' AND passwd=\'";
        sql += passwd;
        sql += "\';";
        return _findUser(sql);
    }

    static bool findUser(const std::string& user)
    {
        std::string sql = "SELECT user FROM login WHERE user=\'";
        sql += user;
        sql += "\';";
        std::cout << "sql: " << sql << std::endl;
        return _findUser(sql);
    }

    static bool _findUser(const std::string& sql)
    {
        MYSQL_RES* code = NULL;
        bool flag = false;
        if (mysql_query(my, sql.c_str()) == 0)
        {
            code = mysql_store_result(my);
            if (mysql_num_rows(code) != 0)
            {
                flag = true;
            }
        }
        mysql_free_result(code);
        return flag;
    }

    static bool insertUser(const std::string& user, const std::string& passwd)
    {
        std::string sql = "INSERT INTO login(user, passwd) VALUES(\'";
        sql += user;
        sql += "\', \'";
        sql += passwd;
        sql += "\');";
        
        return mysql_query(my, sql.c_str()) == 0;
    }
private:
    static MYSQL* my;
    static std::string ip;
    static unsigned int port;
    static std::string user;
    static std::string passwd;
    static std::string db;
};

MYSQL* Util::my = NULL;
std::string Util::ip = "127.0.0.1";
unsigned int Util::port = 3306;
std::string Util::user = "root";
std::string Util::passwd = "fengying66666..";
std::string Util::db = "chat";